import React from 'react';
import { 
  StyleSheet,
  Image,
  Text,
  TouchableOpacity, 
  FlatList,
  View,
  DeviceEventEmitter,
  Alert
} from 'react-native';
import  Icon  from 'react-native-vector-icons/Ionicons'; 
import Modal from "react-native-modal";
import { withNavigationFocus } from "react-navigation";
import { inject, observer } from 'mobx-react';

class MyItem extends React.Component { 
    /**
     * 申请解锁
     */
    _onPress = (data) => {
        if(data.status === 0 && data.type === 2){ 
            this.props.onApplyPress(data);
        }
    }
    /**
     * 当前进度
     */
    _getPrecent = (data) => {
        let res =  (data.cycle - data.last_day) / data.cycle;
        return res.toFixed(2);
    }
    _getWidth = (data) =>{
        return (this._getPrecent(data) * 100) + '%'
    }
    /**
     * 收益记录
     */
    _goProfit = (data) => {
        this.props.navigate('ProfitRecord',{id: data.id, router: 'Hatch' })
    }
    render() { 
        const data = this.props.data.item;  
        // console.warn(data)
        const enumType = ['固定锁仓','灵活锁仓'] //type  锁仓类型(1代表固定锁仓  2代表灵活锁仓)
        const enumStatus = [
            '未解锁',
            '已申请解锁',
            '已经解锁',
            '解锁失败'
        ] // 0表示未解锁  1表示申请解锁  2 表示已经解锁 3解锁失败
      return (
        <View style={styles.resultItem}>
            <View style={styles.resultTxt}>
                <Text>
                    <Text style={styles.c1}>锁仓时间</Text>
                    <Text style={styles.c2}>{data.addtime}</Text>
                </Text>
                {
                    data.type === 1 ?
                    <Text style={styles.cycle}>
                        <Text style={styles.c1}>周期<Text style={styles.c2}>{data.cycle}</Text>天</Text>
                    </Text>
                    :null
                }
            </View>
            <View style={styles.resultCenter}>
                <View style={styles.resultCenterItem}>
                    <Text style={[styles.c2,styles.tc]}>{data.num}</Text>
                    <Text style={[styles.c1,styles.tc]}>孵化数量</Text>
                </View>
                <View style={styles.resultCenterItem}>
                    <Text style={[styles.c2,styles.tc]}>{enumType[data.type - 1]}</Text>
                    <Text style={[styles.c1,styles.tc]}>类型</Text>
                </View>
                <View style={styles.resultCenterItem}>
                    <Text style={[styles.c2,styles.tc]}>{data.accumulated_income}</Text>
                    <Text style={[styles.c1,styles.tc]}>累计收益</Text>
                </View>
            </View>
            {/*<View style={styles.progress}>
             {
                data.type === 1 ?
                <View style={styles.progressBg}>
                    <View style={{
                        backgroundColor:'#FF7F4B',
                        height: 4,
                        width: this._getWidth(data)
                    }}></View>
                </View>
                : null
            }
            </View> */}
            <View style={styles.rsultBtm}>
                <TouchableOpacity onPress={() => this._onPress(data)}>
                    <Text style={(data.status === 0 && data.type === 2) ? styles.c2 : styles.c1}>{(data.status === 0 && data.type === 2) ? '申请解锁' : enumStatus[data.status]}</Text>
                </TouchableOpacity>
                <View style={styles.resultRight}>
                    {
                        data.type === 1 ? 
                            <Text style={styles.c2}><Text style={styles.c1}>(剩余<Text style={styles.c2}>{data.last_day}</Text>天)</Text></Text> 
                            : null
                    }
                    <TouchableOpacity onPress={()=>this._goProfit(data)}>
                        <Text style={styles.c2}>查看收益 ></Text>
                    </TouchableOpacity>
                </View>
            </View>
        </View>
      );
    }
  }

@inject((stores) => {
    return {
        hatchStore: stores.rootStore.hatchStore 
    }
})
@observer class HatchScreen extends React.Component {
    static navigationOptions = {
        header: null,
        headerBackTitle: '返回',
    };
    constructor(props){
		super(props);
        this.subscription = null;
        this.state = { 
            showApplyModal: false,
            lockId: null
        }
    }
    componentDidUpdate(prevProps) {
		if (prevProps.isFocused !== this.props.isFocused && this.props.isFocused) {
		  // Use the `this.props.isFocused` boolean
		  // Call any action
		  //重新获得焦点
		  this._getData();
		}
    }
    componentDidUpdate(prevProps) {
		if (prevProps.isFocused !== this.props.isFocused && this.props.isFocused) {
		  // Use the `this.props.isFocused` boolean
		  // Call any action
		  //重新获得焦点
		  this._getData();
		}
	}
    componentDidMount() {
		this._getData();
		this.subscription = DeviceEventEmitter.addListener('Hatch', this.refreshData)
    }
    componentWillUnmount() {
		this.subscription.remove();
	};
	refreshData = () => {
		this._getData();
    }
    /**
     * 获取数据
     */
    _getData = () => {
        storage.load({ key: 'token' }).then((ret) => {
			if (ret) {
                this.props.hatchStore.getHatchStatisticsData();
                this.props.hatchStore.getHatchListData();
			}else{
				this.props.navigation.navigate('Login')
			}
		}).catch(() => {
			this.props.navigation.navigate('Login')
        });
    }
    /**
     * 显示申请解锁
     */
    _onApplyPress = (data) =>{
        this.setState({
            showApplyModal: true,
            lockId: data.id
        })
    }
    /**
     * 确认申请解锁
     */
    _onLockPress = () => {
        this.props.hatchStore.applyUnlock({id: this.state.lockId},()=>{
            this.props.hatchStore.getHatchListData({page: this.props.hatchStore.currentPage});
            this.setState({
                showApplyModal: false
            })
        })
    }
    /**
     * 上拉加载更多
     */
    _onEndReached = () => {
        let  currentPage = this.props.hatchStore.currentPage;
        let lastPage = this.props.hatchStore.lastPage; 
        if(currentPage >= lastPage){
            return;
        }else {
            this.props.hatchStore.getHatchListData({page: (parseInt(currentPage) + 1)});
        }
    }
    render() {
        const { navigate } = this.props.navigation;  //获取navigation的navigate方法
        return (
            <View style={styles.container}>
                <View style={styles.header}>
                    <Text style={styles.headerTxt}>孵化记录</Text>
                </View>
                <View style={styles.cardMain}>
                    <View style={styles.userCardItem}>
                        <Text style={styles.c3}>{this.props.hatchStore.hatchStatistics.depositsum}</Text>
                        <Text style={styles.userTxtTit}>总孵化数</Text>
                    </View>
                    <View style={styles.userCardItem}>
                        <Text style={styles.c1}>{this.props.hatchStore.hatchStatistics.accumulated}</Text>
                        <Text style={styles.userTxtTit}>累计收益</Text>
                    </View>
                    <View style={styles.userCardItem}>
                        <Text style={styles.c1}>{this.props.hatchStore.hatchStatistics.yesterday_income}</Text>
                        <Text style={styles.userTxtTit}>昨日收益</Text>
                    </View>
                </View>
                <View style={styles.resultMain}> 
                    <View style={styles.result}>
                        {
                            this.props.hatchStore.hatchList.length === 0 ?
                            <View style={{
                                display:'flex',
                                justifyContent:'flex-start',
                                alignContent:'center',
                                alignItems:'center',
                                height: '100%'
                            }}>
                                <Image source={require('../assets/images/kong.png')} style={{width:400 ,height: 400}}></Image>
                            </View>
                            :
                            <FlatList
                                data={this.props.hatchStore.hatchList}
                                keyExtractor={(item, index) => index.toString()}
                                onEndReached={this._onEndReached}
                                renderItem={
                                    (item)=><MyItem data={item} onApplyPress={this._onApplyPress} navigate={this.props.navigation.navigate}></MyItem>
                                }
                            >
                            </FlatList>
                        }
                    </View>
                </View>
                <Modal isVisible={this.state.showApplyModal}>
                    <View style={styles.modalContainer}>
                        <View style={styles.closeBox}>
                            <TouchableOpacity onPress={()=>this.setState({
                                showApplyModal: false
                            })}>
                                <Icon name='ios-close' style={styles.modalClose}></Icon>
                            </TouchableOpacity>
                        </View>
                        <View>
                           <Text style={styles.modalTxt}>解锁后会在24小时自动释放</Text>
                           <View style={styles.btnBox}>
                                <TouchableOpacity onPress={this._onLockPress}>
                                    <View style={styles.btn}>
                                        <Text style={styles.btnTxt}>确定</Text>
                                    </View>
                                </TouchableOpacity>
                           </View>
                        </View>
                    </View>
                </Modal>
            </View>
        );
    }
}
const styles = StyleSheet.create({
	container:{
		flex: 1,
		display: 'flex',
        flexDirection:'column' 
    },
    header:{
        width: '100%',
        display:'flex',
        alignItems: 'center',
        backgroundColor:'#FF7F4B',
		paddingTop: 41,
        height:128
    },
    headerTxt:{
        color:'#FFFFFF',
        fontSize: 18,
    },
    cardMain:{
        marginTop: -35,
        width: '90%',
        marginLeft: 'auto',
        marginRight: 'auto',
        borderColor: '#BBBBBB',
        borderWidth: 1,
        borderRadius: 8,
        height: 100,
        backgroundColor: '#ffffff',
        display:'flex',
        justifyContent:'space-between',
        alignItems:'center',
        flexDirection:'row'
    },
    userCardItem:{
        alignItems:'center',
        width: '33.33%',
        textAlign:'center'
    },
    c3:{
        color:'#E51C23',
        fontSize: 14
    },
    c2:{
        color:'#FF7F4B',
        fontSize: 14
    },
    c1:{
        color:'#B9B6B6',
        fontSize: 14
    },
    userTxtTit:{
        color:'#B9B6B6',
        fontSize: 14,
        marginTop: 10
    },
    resultMain:{
        flex: 12,
        flexDirection:'column'
    },
    result:{
        width: '90%',
        marginLeft: 'auto',
        marginRight:'auto'
    },
    resultItem:{
        borderWidth: 1,
        borderColor:'#B9B6B6',
        borderRadius: 8,
        marginTop: 13,
        paddingBottom: 10,
    },
    resultTxt:{
        display:'flex',
        flexDirection:'row',
        paddingLeft: 10,
        lineHeight: 19,
        marginTop: 5,
        justifyContent:'space-between'
    },
    resultCenter:{
        marginTop: 5,
        display:'flex',
        flexDirection:'row',
        justifyContent:'space-between',
        alignItems:'center',
        paddingLeft:5,
        paddingRight: 5,
    },
    tc:{
        textAlign:'center'
    },
    progress:{
        height:4,
        marginTop: 10,
        marginBottom: 10,
        paddingLeft: 5,
        paddingRight: 5
    },
    progressBg:{
        backgroundColor:'#B9B6B6',
        height: 4,
        width: '100%'
    },
    progressValue:{
        backgroundColor:'#FF7F4B',
        height: 4,
        width: '37%'
    },
    rsultBtm:{
        display:'flex',
        justifyContent:'space-between',
        flexDirection:'row',
        paddingLeft:5,
        paddingRight: 5
    },
    modalTxt:{
        color:'#FF7F4B',
        fontSize: 14,
        textAlign:'center'
    },
    modalContainer:{ 
        backgroundColor: 'rgba(232, 229, 229, 0.8)',
        padding: 10,
        borderRadius: 8,
        paddingBottom: 20
    },
    btn:{
        width: 80,
        height: 30,
        lineHeight: 30,
        backgroundColor:'#FF7F4B',
        textAlign:'center',
        borderRadius: 8,
        marginTop: 20,
        marginLeft: 'auto',
        marginRight: 'auto'
    },
    btnTxt:{
        fontSize: 16,
        color: '#ffffff',
        lineHeight: 30,
        textAlign:'center'
    },
    closeBox:{
        display:'flex',
        justifyContent:'flex-end',
        alignItems:'flex-end'
    },
    modalClose:{
        color:'#ffffff',
        fontSize:30
    },
    btnBox:{
        textAlign:'center'
    },
    resultRight:{
        display:'flex',
        justifyContent:'flex-start',
        flexDirection:'row'
    }
});
export default withNavigationFocus(HatchScreen);
